package tips

import (
	"context"
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"sync"
	"time"
)

func worker(cancel chan struct{}) {
	for {
		select {
		default:
			fmt.Println(time.Now())
			time.Sleep(100 * time.Millisecond)
		case <-cancel:
			fmt.Println("got signal,exit ...")
			close(cancel)
			return
		}
	}
}

func CancelWithChannel() {
	cancel := make(chan struct{})
	go worker(cancel)
	time.Sleep(time.Second)
	cancel <- struct{}{}
}

func worker2(wg *sync.WaitGroup, cancel chan bool) {
	defer wg.Done()
	for {
		select {
		default:
			fmt.Println("hello")
			time.Sleep(100 * time.Millisecond)
		case <-cancel:
			return
		}
	}
}

func CancelWithDown() {
	cancel := make(chan bool)
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go worker2(&wg, cancel)
	}
	time.Sleep(time.Second)
	close(cancel)
	wg.Wait()
}

func worker3(ctx context.Context, wg *sync.WaitGroup) error {
	defer wg.Done()
	for {
		select {
		default:
			fmt.Println("Hello")
			time.Sleep(100 * time.Millisecond)
		case <-ctx.Done():
			return ctx.Err()
		}
	}
}

func CancelWithCtx() {
	start := time.Now()
	defer func() {
		fmt.Print(time.Since(start).Seconds())
	}()

	//控制超时
	ctx, _ := context.WithTimeout(context.Background(), 2*time.Second)

	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go worker3(ctx, &wg)
	}
	//cancel()
	wg.Wait()
}

func GetMd5(pwd string) string {
	h := md5.New()       //初始化返回哈希对象
	h.Write([]byte(pwd)) //把string类型的pwd转换成无符号uint8类型，Wirte函数再转成int类型

	return hex.EncodeToString(h.Sum(nil))

}
